package com.mz.ozy.activity.shop;

import androidx.annotation.Nullable;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.mz.ozy.R;
import com.mz.ozy.activity.home.DeliveryListActivity;
import com.mz.ozy.activity.me.AddressActivity;
import com.mz.ozy.activity.me.PayPwdActivity;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.AddressBean;
import com.mz.ozy.bean.CarInfoBean;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.FirmGoodsBean;
import com.mz.ozy.bean.FirmOrderBean;
import com.mz.ozy.bean.NetBean;
import com.mz.ozy.bean.OrderBean;
import com.mz.ozy.bean.ScheduledOrderBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.ScheduledOrderPresenter;
import com.mz.ozy.mvp.view.ScheduledOrderContract;
import com.mz.ozy.utils.CalendarUtils;
import com.mz.ozy.utils.PayManager;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.utils.glideUtils.GlideUtils;
import com.mz.ozy.widget.dialog.PaySelectDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ScheduledOrderActivity extends BaseActivity<ScheduledOrderContract.View, ScheduledOrderPresenter> implements ScheduledOrderContract.View {

    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_empty)
    TextView mTvEmpty;
    @BindView(R.id.tv_default)
    TextView mTvDefault;
    @BindView(R.id.tv_mobile)
    TextView mTvMobile;
    @BindView(R.id.tv_address)
    TextView mTvAddress;
    @BindView(R.id.rl_address)
    RelativeLayout mRlAddress;
    //    @BindView(R.id.rv_goods_list)
//    RecyclerView mRvGoodsList;
    @BindView(R.id.rv_goods_list)
    LinearLayout mRvGoodsList;
    @BindView(R.id.rv_presales_list)
    LinearLayout mRvPresaleList;
    @BindView(R.id.ll_goods_content)
    LinearLayout mLlGoodsContent;
    @BindView(R.id.tv_goods_count)
    TextView mTvGoodsCount;
    @BindView(R.id.rl_goods_list)
    RelativeLayout mRlGoodsList;
    @BindView(R.id.ll_user_info)
    LinearLayout mLlUserInfo;
    @BindView(R.id.tv_freight_count)
    TextView mTvFreightCount;
    @BindView(R.id.ll_freight)
    LinearLayout mLlFreight;
    @BindView(R.id.tv_real_payment)
    TextView mTvRealPayment;
    @BindView(R.id.iv_firm_right)
    ImageView mIvFirmRight;
    @BindView(R.id.iv_firm_location)
    ImageView mIvFirmLocation;
    @BindView(R.id.btn_submit)
    Button mBtnSubmit;
    @BindView(R.id.et_remark)
    EditText mEtRemark;
    @BindView(R.id.tv_express_delivery)
    TextView mTvExpressDelivery;
    private ScheduledOrderBean mFirmOrderBean;
    private List<FirmGoodsBean> mFirmGoodsBeans = new ArrayList<>();
    private List<FirmOrderBean.ProductMapBean> goodsList = new ArrayList<>();
    private List<TextView> mTextViews = new ArrayList<>();
    private double mTotalPriceW;
    private int mGoodsNum;
    private double mTotalPrice;
    private double mTotalMarketPrice;
    private String mCid;
    private String mGid;//商品id  详情发起的立即购买
    private String mAid;
    private int mArea0id;
    private int mArea1id;
    private int mArea2id;
    private double mFreight = 0.00;
    private long curTime;
    private boolean hasAddress = false;
    private boolean hasDefaultAddress = false;
    private int payType;
    private PayManager mPayManager;

    /**
     * @param context
     * @param firmOrderBean 订单信息
     * @param cid           购物车Id
     * @param gid           商品id
     */

    public static void start(Context context, ScheduledOrderBean firmOrderBean, String cid, String gid) {
        Intent starter = new Intent(context, ScheduledOrderActivity.class);
        starter.putExtra("firmOrderBean", firmOrderBean);
        starter.putExtra("cid", cid);
        starter.putExtra("gid", gid);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scheduled_order);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initData();
        initTitle();
        init();
        if (hasAddress) {
            initFreight(mFirmOrderBean.getCarList(), mTvExpressDelivery);
        } else {
            mTvExpressDelivery.setText("运费 ¥0.0");
        }
        if (hasAddress) {
            mTotalPriceW = mTotalPrice + mFreight;
        } else {
            mTotalPriceW = mTotalPrice;
        }
        mTvRealPayment.setText(getPrice(mTotalPriceW));
    }

    protected void onResume() {
        super.onResume();
        PayManager.pay_from = 2;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        //刷新购物车
        if ((event.getCode() == Constants.EventCode.WX_PAY_SUCCESS || event.getCode() == Constants.EventCode.ALIPAY_PAY_SUCCESS)
                && PayManager.pay_from == 2) {
            ToastUtils.showToast("支付成功");
            finish();

            Intent starter = new Intent(this, DeliveryListActivity.class);
            startActivity(starter);
        }
        if ((event.getCode() == Constants.EventCode.JUMP_PAY_PWD)) {
            startActivity(new Intent(this, PayPwdActivity.class));
        }
        if (event.getCode() == Constants.EventCode.CHANGE_DEFAULT_ADDRESS) {
            final AddressBean addressBean = (AddressBean) event.getData();
            reLoadAddressMap(addressBean);
            if (mAid.equals("-1")) {
                hasDefaultAddress = true;
                reLoadCurAddress(addressBean);
            } else {
                if (mAid.equals(addressBean.getId())) {
                    mTvDefault.setVisibility(View.VISIBLE);
                } else {
                    mTvDefault.setVisibility(View.GONE);
                }
            }
        }
        if (event.getCode() == Constants.EventCode.EDIT_ADDRESS) {
            final AddressBean addressBean = (AddressBean) event.getData();
            if (addressBean.getId() == mFirmOrderBean.getShaddressMap().getId()) {
                reLoadAddressMap(addressBean);
            }
            reLoadCurAddress(addressBean);
        }
        if (event.getCode() == Constants.EventCode.DELETE_DEFAULT_ADDRESS) {
            hasDefaultAddress = false;
            if (mAid.equals(mFirmOrderBean.getShaddressMap().getId() + "")) {
                reLoadNoAddress();
            }
        } else if (event.getCode() == Constants.EventCode.DELETE_ADDRESS) {
            if (hasDefaultAddress) {
                reLoadDefaultAddressAndFreight();
            } else {
                reLoadNoAddress();
            }
        }
    }

    private void reLoadDefaultAddressAndFreight() {
        reLoadDefaultAddress();
        hasAddress = true;
        reLoadFreight();
        if (hasAddress) {
            initFreight(mFirmOrderBean.getCarList(), mTvExpressDelivery);
        } else {
            mTvExpressDelivery.setText("运费 ¥0.0");
        }
        if (!hasAddress) {
            mTotalPriceW = mTotalPrice;
        } else {
            mTotalPriceW = mTotalPrice + mFreight;
        }
        mTvRealPayment.setText(getPrice(mTotalPriceW));
    }

    private void reLoadCurAddress(AddressBean bean) {
        mLlUserInfo.setVisibility(View.VISIBLE);
        mTvEmpty.setVisibility(View.GONE);
        mIvFirmRight.setImageResource(R.mipmap.firm_right_arrow);
        mIvFirmLocation.setVisibility(View.VISIBLE);
        mTvName.setText(bean.getConsignee());
        final String contactnumber = bean.getContactnumber();
        final String phonestr = contactnumber.substring(0, 3) + "****" + contactnumber.substring(contactnumber.length() - 4);
        mTvMobile.setText(phonestr);
        if (1 == bean.getIsdefault()) {
            mTvDefault.setVisibility(View.VISIBLE);
        } else {
            mTvDefault.setVisibility(View.GONE);
        }
        String address = "";
        if (bean.getArea0id().equals(bean.getArea1id())) {
            address = bean.getArea1name() + bean.getArea2name() + bean.getXxaddress();
        } else {
            address = bean.getArea0name() + bean.getArea1name() + bean.getArea2name() + bean.getXxaddress();
        }
        mTvAddress.setText(address);
        mAid = String.valueOf(bean.getId());
        mArea0id = Integer.parseInt(bean.getArea0id());
        mArea1id = Integer.parseInt(bean.getArea1id());
        mArea2id = Integer.parseInt(bean.getArea2id());
        hasAddress = true;
        reLoadFreight();
        if (hasAddress) {
            initFreight(mFirmOrderBean.getCarList(), mTvExpressDelivery);
        } else {
            mTvExpressDelivery.setText("运费 ¥0.0");
        }
        if (!hasAddress) {
            mTotalPriceW = mTotalPrice;
        } else {
            mTotalPriceW = mTotalPrice + mFreight;
        }
        mTvRealPayment.setText(getPrice(mTotalPriceW));
    }

    private void reLoadAddressMap(AddressBean addressBean) {
        mFirmOrderBean.getShaddressMap().setId(addressBean.getId());
        mFirmOrderBean.getShaddressMap().setArea0id(Integer.parseInt(addressBean.getArea0id()));
        mFirmOrderBean.getShaddressMap().setArea1id(Integer.parseInt(addressBean.getArea1id()));
        mFirmOrderBean.getShaddressMap().setArea2id(Integer.parseInt(addressBean.getArea2id()));
        mFirmOrderBean.getShaddressMap().setArea0name(addressBean.getArea0name());
        mFirmOrderBean.getShaddressMap().setArea1name(addressBean.getArea1name());
        mFirmOrderBean.getShaddressMap().setArea2name(addressBean.getArea2name());
        mFirmOrderBean.getShaddressMap().setXxaddress(addressBean.getXxaddress());
        mFirmOrderBean.getShaddressMap().setContactnumber(addressBean.getContactnumber());
        mFirmOrderBean.getShaddressMap().setConsignee(addressBean.getConsignee());
        mFirmOrderBean.getShaddressMap().setIsdefault(addressBean.getIsdefault());
    }

    private void reLoadNoAddress() {
        mLlUserInfo.setVisibility(View.GONE);
        mTvAddress.setText("");
        mIvFirmLocation.setVisibility(View.GONE);
        mIvFirmRight.setImageResource(R.mipmap.empty_right_arrow);
        mTvEmpty.setVisibility(View.VISIBLE);
        hasAddress = false;
        mAid = "-1";
        reLoadFreight();
        if (hasAddress) {
            initFreight(mFirmOrderBean.getCarList(), mTvExpressDelivery);
        } else {
            mTvExpressDelivery.setText("运费 ¥0.0");
        }
        if (!hasAddress) {
            mTotalPriceW = mTotalPrice;
        } else {
            mTotalPriceW = mTotalPrice + mFreight;
        }
        mTvRealPayment.setText(getPrice(mTotalPriceW));
    }

    private void initData() {
        mFirmOrderBean = (ScheduledOrderBean) getIntent().getSerializableExtra("firmOrderBean");
        mCid = getIntent().getStringExtra("cid");
        mGid = getIntent().getStringExtra("gid");
        if (mFirmOrderBean == null && TextUtils.isEmpty(mCid)) {
            ToastUtils.showToast("数据有误");
            finish();
        }
        mArea0id = mFirmOrderBean.getShaddressMap().getArea0id();
        mArea1id = mFirmOrderBean.getShaddressMap().getArea1id();
        mArea2id = mFirmOrderBean.getShaddressMap().getArea2id();
        if (mArea0id == 0 && mArea1id == 0 && mArea2id == 0) {
            hasAddress = false;
        } else {
            hasAddress = true;
        }
        mPayManager = new PayManager(this);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        Date curDate = cal.getTime();
        curTime = curDate.getTime();
    }

    private void initFreight(List<FirmOrderBean.ProductMapBean> carList, TextView tvExpressDelivery) {
        mFreight = 0.00;
        if (!TextUtils.isEmpty(mCid)) {
            if (carList != null && carList.size() > 0) {
                for (FirmOrderBean.ProductMapBean tmpMapBean : carList) {
                    if (tmpMapBean.getFreightList() != null && tmpMapBean.getFreightList().size() > 0) {
                        for (FirmOrderBean.FreightMapBean freightMapBean : tmpMapBean.getFreightList()) {
                            boolean isSame = compareFreight(freightMapBean.getArea());
                            if (isSame) {
                                tmpMapBean.setFreightid(freightMapBean.getId());
                                tmpMapBean.setType(freightMapBean.getType());
                                tmpMapBean.setAmount(freightMapBean.getAmount());
                                tmpMapBean.setContinuation(freightMapBean.getContinuation());
                                break;
                            }
                        }
                        double tmpFreight = 0.0;
                        if (tmpMapBean.getType() == 0) {
                            tmpFreight = Double.parseDouble(tmpMapBean.getAmount());
                            if (tmpMapBean.getNum() > 1) {
                                final int spaceNum = tmpMapBean.getNum() - 1;
                                tmpFreight = tmpFreight + Double.parseDouble(tmpMapBean.getContinuation()) * spaceNum;
                            }
                        } else if (tmpMapBean.getType() == 1) {
                            tmpFreight = 0.0;
                        } else {
                            final String ggweight = tmpMapBean.getFreWeight();
                            double totalWeight = Double.parseDouble(ggweight) * tmpMapBean.getNum();
                            if (totalWeight <= 1.0) {
                                tmpFreight = Double.parseDouble(tmpMapBean.getAmount());
                            } else {
                                tmpFreight = Double.parseDouble(tmpMapBean.getAmount());
                                double spaceWeight = totalWeight - 1.0;
                                final double times = Math.ceil(spaceWeight / 1.0);
                                tmpFreight = tmpFreight + Double.parseDouble(tmpMapBean.getContinuation()) * times;
                            }
                        }
                        mFreight += tmpFreight;
                    }
                }
//                if (tvExpressDelivery != null) {
//                    if (mFreight != 0.00) {
//                        tvExpressDelivery.setText("运费 " + "¥" + Utils.subTwoNumber(mFreight));
//                    } else {
//                        tvExpressDelivery.setText("包邮");
//                    }
//                }
            }
        } else if (!TextUtils.isEmpty(mGid)) {
            final List<FirmOrderBean.FreightMapBean> freightList = mFirmOrderBean.getFreightList();
            if (freightList != null && freightList.size() > 0) {
                for (FirmOrderBean.FreightMapBean freightMapBean : freightList) {
                    boolean isSame = compareFreight(freightMapBean.getArea());
                    if (isSame) {
                        mFirmOrderBean.setFreightid(freightMapBean.getId());
                        mFirmOrderBean.setType(freightMapBean.getType());
                        mFirmOrderBean.setFreight(freightMapBean.getAmount());
                        mFirmOrderBean.setContinuation(freightMapBean.getContinuation());
                        break;
                    }
                }
                double tmpFreight = 0.0;
                if (mFirmOrderBean.getType() == 0) {
                    tmpFreight = Double.parseDouble(mFirmOrderBean.getFreight());
                    if (mGoodsNum > 1) {
                        final int spaceNum = mGoodsNum - 1;
                        tmpFreight = tmpFreight + Double.parseDouble(mFirmOrderBean.getContinuation()) * spaceNum;
                    }
                } else if (mFirmOrderBean.getType() == 1) {
                    tmpFreight = 0.0;
                } else {
                    final String ggweight = mFirmOrderBean.getGmap().getWeight();
                    double totalWeight = Double.parseDouble(ggweight) * mGoodsNum;
                    if (totalWeight <= 1.0) {
                        tmpFreight = Double.parseDouble(mFirmOrderBean.getFreight());
                    } else {
                        tmpFreight = Double.parseDouble(mFirmOrderBean.getFreight());
                        double spaceWeight = totalWeight - 1.0;
                        final double times = Math.ceil(spaceWeight / 1.0);
                        tmpFreight = tmpFreight + Double.parseDouble(mFirmOrderBean.getContinuation()) * times;
                    }
                }
                mFreight = tmpFreight;
                if (tvExpressDelivery != null) {
                    if (mFreight != 0.00) {
                        tvExpressDelivery.setText("运费 " + "¥" + Utils.subTwoNumber(mFreight));
                    } else {
                        tvExpressDelivery.setText("包邮");
                    }
                }
            }
        }
    }

    private double proccessGoodsFreight(int carNum) {
        double curFreight = 0.0;
        final List<FirmOrderBean.FreightMapBean> freightList = mFirmOrderBean.getFreightList();
        if (freightList != null && freightList.size() > 0) {
            for (FirmOrderBean.FreightMapBean freightMapBean : freightList) {
                boolean isSame = compareFreight(freightMapBean.getArea());
                if (isSame) {
                    mFirmOrderBean.setFreightid(freightMapBean.getId());
                    mFirmOrderBean.setType(freightMapBean.getType());
                    mFirmOrderBean.setFreight(freightMapBean.getAmount());
                    mFirmOrderBean.setContinuation(freightMapBean.getContinuation());
                    break;
                }
            }
            if (mFirmOrderBean.getType() == 0) {
                curFreight = Double.parseDouble(mFirmOrderBean.getFreight());
                if (carNum > 1) {
                    final int spaceNum = carNum - 1;
                    curFreight = curFreight + Double.parseDouble(mFirmOrderBean.getContinuation()) * spaceNum;
                }
            } else if (mFirmOrderBean.getType() == 1) {
                curFreight = 0.0;
            } else {
                final String ggweight = mFirmOrderBean.getGmap().getWeight();
                double totalWeight = Double.parseDouble(ggweight) * carNum;
                if (totalWeight <= 1.0) {
                    curFreight = Double.parseDouble(mFirmOrderBean.getFreight());
                } else {
                    curFreight = Double.parseDouble(mFirmOrderBean.getFreight());
                    double spaceWeight = totalWeight - 1.0;
                    final double times = Math.ceil(spaceWeight / 1.0);
                    curFreight = curFreight + Double.parseDouble(mFirmOrderBean.getContinuation()) * times;
                }
            }
        }
        return curFreight;
    }

    private double proccessCarFreight(List<FirmOrderBean.ProductMapBean> carList) {
        double curFreight = 0.0;
        if (carList != null && carList.size() > 0) {
            for (FirmOrderBean.ProductMapBean tmpMapBean : carList) {
                if (tmpMapBean.getFreightList() != null && tmpMapBean.getFreightList().size() > 0) {
                    for (FirmOrderBean.FreightMapBean freightMapBean : tmpMapBean.getFreightList()) {
                        boolean isSame = compareFreight(freightMapBean.getArea());
                        if (isSame) {
                            tmpMapBean.setFreightid(freightMapBean.getId());
                            tmpMapBean.setType(freightMapBean.getType());
                            tmpMapBean.setAmount(freightMapBean.getAmount());
                            tmpMapBean.setContinuation(freightMapBean.getContinuation());
                            break;
                        }
                    }
                    double tmpFreight = 0.0;
                    if (tmpMapBean.getType() == 0) {
                        tmpFreight = Double.parseDouble(tmpMapBean.getAmount());
                        if (tmpMapBean.getNum() > 1) {
                            final int spaceNum = tmpMapBean.getNum() - 1;
                            tmpFreight = tmpFreight + Double.parseDouble(tmpMapBean.getContinuation()) * spaceNum;
                        }
                    } else if (tmpMapBean.getType() == 1) {
                        tmpFreight = 0.0;
                    } else {
                        final String ggweight = tmpMapBean.getFreWeight();
                        double totalWeight = Double.parseDouble(ggweight) * tmpMapBean.getNum();
                        if (totalWeight <= 1.0) {
                            tmpFreight = Double.parseDouble(tmpMapBean.getAmount());
                        } else {
                            tmpFreight = Double.parseDouble(tmpMapBean.getAmount());
                            double spaceWeight = totalWeight - 1.0;
                            final double times = Math.ceil(spaceWeight / 1.0);
                            tmpFreight = tmpFreight + Double.parseDouble(tmpMapBean.getContinuation()) * times;
                        }
                    }
                    curFreight += tmpFreight;
                }
            }
        }
        return curFreight;
    }


    private boolean compareFreight(String area) {
        final String[] areaArr = area.split(",");
        boolean oneSame = false;
        boolean twoSame = false;
        boolean threeSame = false;
        String oneArea = mArea0id + "";
        String twoArea = mArea1id + "";
        String threeArea = mArea2id + "";
        if (areaArr != null && areaArr.length > 0) {
            for (String tmparea : areaArr) {
                if (oneArea.equals(tmparea)) {
                    oneSame = true;
                }
                if (twoArea.equals(tmparea)) {
                    twoSame = true;
                }
                if (threeArea.equals(tmparea)) {
                    threeSame = true;
                }
                if (oneSame == true || twoSame == true || threeSame == true) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void onSubmitSuccess(OrderBean orderBean) {
//        OrderPayActivity.start(this, orderBean.getOrderNo());
//        EventBus.getDefault().post(new EventBean(Constants.EventCode.REFRESH_CAR, null));
//        finish();
        EventBus.getDefault().post(new EventBean(Constants.EventCode.SCHEDULED_ORDER_SUCCESS, null));
        showSportsHarmDialog(orderBean);
    }

    @Override
    public void handleFailResponse(NetBean bean) {
        super.handleFailResponse(bean);
        if (Constants.TransCode.TransCode10086.equals(bean.getTransCode())) {
            finish();
            Intent starter = new Intent(this, DeliveryListActivity.class);
            startActivity(starter);
        }
    }

    @Override
    public void onPaySuccess(JSONObject orderBean) {
        if (payType == 0) { //余额支付
            ToastUtils.showToast("支付成功");
            finish();
            Intent starter = new Intent(this, DeliveryListActivity.class);
            startActivity(starter);
        } else if (payType == 2) {  //微信支付
            mPayManager.handleWxPay(orderBean);
        } else if (payType == 1) {  //支付宝支付
            mPayManager.handleAliPay(orderBean.optString("zfb"));
        }

    }

    @Override
    public void onPayError(String s) {
        finish();
        Intent starter = new Intent(this, DeliveryListActivity.class);
        startActivity(starter);
    }

    @Override
    public void onSubmitError(String msg) {
    }

    private void init() {
        tvCenterTitle.setText("确认订单");
        mAid = "-1";
        if (TextUtils.isEmpty(mFirmOrderBean.getShaddressMap().getConsignee())) {
            hasDefaultAddress = false;
            mLlUserInfo.setVisibility(View.GONE);
            mTvAddress.setText("");
            mIvFirmLocation.setVisibility(View.GONE);
            mTvEmpty.setVisibility(View.VISIBLE);
            mIvFirmRight.setImageResource(R.mipmap.empty_right_arrow);
        } else {
            hasDefaultAddress = true;
            mTvEmpty.setVisibility(View.GONE);
            mIvFirmRight.setVisibility(View.VISIBLE);
            mIvFirmLocation.setVisibility(View.VISIBLE);
            reLoadDefaultAddress();
        }
        processCarList();
        final CarInfoBean carInfoBean = getCarInfoBean(mFirmOrderBean.getCarList());
        mTotalPrice = carInfoBean.getTotalPrice();
        mTotalMarketPrice = carInfoBean.getTotalMarketPrice();
        mGoodsNum = carInfoBean.getNum();
//        if (mFirmOrderBean.getKtmap() != null) {
//            final String integral = mFirmOrderBean.getKtmap().getIntegral();
//        }
    }

    private void reLoadDefaultAddress() {
        mTvName.setText(mFirmOrderBean.getShaddressMap().getConsignee());
        final String contactnumber = mFirmOrderBean.getShaddressMap().getContactnumber();
        final String phonestr = contactnumber.substring(0, 3) + "****" + contactnumber.substring(contactnumber.length() - 4);
        mTvMobile.setText(phonestr);
        mAid = String.valueOf(mFirmOrderBean.getShaddressMap().getId());
        mArea0id = mFirmOrderBean.getShaddressMap().getArea0id();
        mArea1id = mFirmOrderBean.getShaddressMap().getArea1id();
        mArea2id = mFirmOrderBean.getShaddressMap().getArea2id();
        String address = "";
        if (mArea0id == mArea1id) {
            address = mFirmOrderBean.getShaddressMap().getArea1name() + mFirmOrderBean.getShaddressMap().getArea2name() + mFirmOrderBean.getShaddressMap().getXxaddress();
        } else {
            address = mFirmOrderBean.getShaddressMap().getArea0name() + mFirmOrderBean.getShaddressMap().getArea1name() + mFirmOrderBean.getShaddressMap().getArea2name() + mFirmOrderBean.getShaddressMap().getXxaddress();
        }
        mTvAddress.setText(address);
        if (1 == mFirmOrderBean.getShaddressMap().getIsdefault()) {
            mTvDefault.setVisibility(View.VISIBLE);
        } else {
            mTvDefault.setVisibility(View.GONE);
        }
    }

    private CarInfoBean getCarInfoBean(List<FirmOrderBean.ProductMapBean> carList) {
        double totalPrice = 0.00;
        double totalMarketPrice = 0.00;
        int num = 0;
        for (FirmOrderBean.ProductMapBean mapBean : carList) {
            num += mapBean.getNum();
            double price = 0.00;
            if (!TextUtils.isEmpty(mapBean.getPrice())) {
                price = Double.parseDouble(mapBean.getPrice());
            }
            double marketPrice = 0.00;
            if (!TextUtils.isEmpty(mapBean.getMarketPrice())) {
                marketPrice = Double.parseDouble(mapBean.getMarketPrice());
            }
            totalPrice = totalPrice + price * mapBean.getNum();
            totalMarketPrice = totalMarketPrice + marketPrice * mapBean.getNum();
        }
        return new CarInfoBean(totalPrice, totalMarketPrice, num);
    }

    private void processCarList() {
        if (mFirmOrderBean.getCarList() != null) {
            for (FirmOrderBean.ProductMapBean productMapBean : mFirmOrderBean.getCarList()) {
                if (!TextUtils.isEmpty(productMapBean.getStarttime())) {
                    Date date = null;
                    try {
                        date = CalendarUtils.string2Date(productMapBean.getStarttime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (curTime < date.getTime()) {
                        FirmGoodsBean firmGoodsBeanList = getFirmGoodsBeanList(productMapBean.getStarttime());
                        if (firmGoodsBeanList == null) {
                            firmGoodsBeanList = new FirmGoodsBean();
                            firmGoodsBeanList.setDate(productMapBean.getStarttime());
                            firmGoodsBeanList.addProduct(productMapBean);
                            mFirmGoodsBeans.add(firmGoodsBeanList);
                        } else {
                            firmGoodsBeanList.addProduct(productMapBean);
                        }
                    } else {
                        goodsList.add(productMapBean);
                    }
                } else {
                    goodsList.add(productMapBean);
                }
            }
            processGoodsList();
            processPresalesList();
        }
    }

    private void processPresalesList() {
        if (mFirmGoodsBeans.size() == 0) {
            mRvPresaleList.setVisibility(View.GONE);
        } else {
            for (FirmGoodsBean firmGoodsBean : mFirmGoodsBeans) {
                final View presaleOrderView = View.inflate(this, R.layout.item_firm_order_presale, null);
                mRvPresaleList.addView(presaleOrderView);
                processPresalesView(presaleOrderView, firmGoodsBean);
                LinearLayout rvPresaleList = presaleOrderView.findViewById(R.id.rv_presale_goods_list);
                if (firmGoodsBean.getCarList().size() == 0) {
                    rvPresaleList.setVisibility(View.GONE);
                } else {
                    for (FirmOrderBean.ProductMapBean productMapBean : firmGoodsBean.getCarList()) {
                        final View submitOrderView = View.inflate(this, R.layout.item_submit_order_view, null);
                        processSubmitOrderView(submitOrderView, rvPresaleList, productMapBean);
                    }
                    final CarInfoBean carInfoBean = getCarInfoBean(firmGoodsBean.getCarList());
                    TextView tvGoodsCount = presaleOrderView.findViewById(R.id.tv_presale_count);
                    TextView tvFreightCount = presaleOrderView.findViewById(R.id.tv_presale_freight);
                    TextView tvExpressDelivery = presaleOrderView.findViewById(R.id.tv_presale_delivery);
                    //共多少件
                    tvGoodsCount.setText("共" + carInfoBean.getNum() + "件  商品金额:");
                    tvFreightCount.setText(getPrice(carInfoBean));
                    double goodsFreight = 0.0;
                    if (!TextUtils.isEmpty(mCid)) {
                        goodsFreight = proccessCarFreight(firmGoodsBean.getCarList());
                    } else if (!TextUtils.isEmpty(mGid)) {
                        goodsFreight = proccessGoodsFreight(carInfoBean.getNum());
                    }
                    if (goodsFreight != 0.00) {
                        tvExpressDelivery.setText("运费 ¥" + Utils.subTwoNumber(goodsFreight));
                    } else {
                        if (hasAddress) {
                            tvExpressDelivery.setText("包邮");
                        } else {
                            tvExpressDelivery.setText("运费 ¥0.0");
                        }
                    }
                    mTextViews.add(tvExpressDelivery);
                }
            }
        }
    }

    private void processPresalesView(View presaleOrderView, FirmGoodsBean firmGoodsBean) {
        final TextView tvPresaleTime = presaleOrderView.findViewById(R.id.tv_presale_time);
        final String formatDate = firmGoodsBean.getFormatDate();
        tvPresaleTime.setText("开售时间" + formatDate);
    }

    private void processGoodsList() {
        if (goodsList.size() == 0) {
            mLlGoodsContent.setVisibility(View.GONE);
        } else {
            for (FirmOrderBean.ProductMapBean productMapBean : goodsList) {
                final View submitOrderView = View.inflate(this, R.layout.item_submit_order_view, null);
                processSubmitOrderView(submitOrderView, mRvGoodsList, productMapBean);
            }
            final CarInfoBean carInfoBean = getCarInfoBean(goodsList);
            //共多少件
            mTvGoodsCount.setText("共" + carInfoBean.getNum() + "件  商品金额:");
            mTvFreightCount.setText(getPrice(carInfoBean));
            if (!TextUtils.isEmpty(mCid)) {
                final double goodsFreight = proccessCarFreight(goodsList);
                if (goodsFreight != 0.00) {
                    mTvExpressDelivery.setText("运费 ¥" + Utils.subTwoNumber(goodsFreight));
                } else {
                    if (hasAddress) {
                        mTvExpressDelivery.setText("包邮");
                    } else {
                        mTvExpressDelivery.setText("运费 ¥0.0");
                    }
                }
            }
        }
    }

    private void processSubmitOrderView(View submitOrderView, LinearLayout rvGoodsList, FirmOrderBean.ProductMapBean productMapBean) {
        rvGoodsList.addView(submitOrderView);
        ImageView ivIcon = submitOrderView.findViewById(R.id.iv_only_goods_icon);
        final String img_zt = productMapBean.getImg_zt();
        final String imgZt = productMapBean.getImgZt();
        if (!TextUtils.isEmpty(img_zt)) {
            final String[] img_ztarr = img_zt.trim().split(",");
            Glide.with(this).load(img_ztarr[0])
                    .transition(DrawableTransitionOptions.withCrossFade())//适用于Drawable
                    .into(ivIcon);
        } else if (!TextUtils.isEmpty(imgZt)) {
            final String[] img_ztarr = imgZt.trim().split(",");
            Glide.with(this).load(img_ztarr[0])
                    .transition(DrawableTransitionOptions.withCrossFade())//适用于Drawable
                    .into(ivIcon);
        } else {
            GlideUtils.loadImg(this, ivIcon, R.mipmap.logo);
        }
        TextView goodsTitle = submitOrderView.findViewById(R.id.tv_only_goods_title);
        if (!TextUtils.isEmpty(productMapBean.getTradename())) {
            goodsTitle.setText(productMapBean.getTradename());
        } else {
            goodsTitle.setText(productMapBean.getProductName());
        }
        TextView goodsinfo = submitOrderView.findViewById(R.id.tv_only_goods_info);
        goodsinfo.setText(productMapBean.getgName());
        TextView tvPrice = submitOrderView.findViewById(R.id.tv_goods_price);
        tvPrice.setText(getPrice(productMapBean));
        TextView tvCount = submitOrderView.findViewById(R.id.tv_count);
        tvCount.setText("×" + productMapBean.getNum());
    }

    private FirmGoodsBean getFirmGoodsBeanList(String starttime) {
        for (FirmGoodsBean firmGoodsBean : mFirmGoodsBeans) {
            if (!TextUtils.isEmpty(firmGoodsBean.getDate()) && firmGoodsBean.getDate().equals(starttime)) {
                return firmGoodsBean;
            }
        }
        return null;
    }

    @NotNull
    private String getPrice(CarInfoBean item) {
        String price = "";
        if (item.getTotalPrice() != 0.00) {
            price += "¥";
            price += Utils.subTwoNumber(item.getTotalPrice());
        }
        if (item.getTotalMarketPrice() != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += Utils.subTwoNumber(item.getTotalMarketPrice());
                price += "积分";
            } else {
                price += Utils.subTwoNumber(item.getTotalMarketPrice());
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }
        return price;
    }

    @NotNull
    private String getPrice(FirmOrderBean.ProductMapBean item) {
        String price = "";
        if (!TextUtils.isEmpty(item.getPrice()) && Double.parseDouble(item.getPrice()) != 0.00) {
            price += "¥";
            price += item.getPrice();
        }
        if (!TextUtils.isEmpty(item.getMarketPrice()) && Double.parseDouble(item.getMarketPrice()) != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += item.getMarketPrice();
                price += "积分";
            } else {
                price += item.getMarketPrice();
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }
        return price;
    }

    private String getPriceSpace(double totalPrice) {
        String price = "";
        if (totalPrice != 0.00) {
            price += Utils.subTwoNumber(totalPrice);
        }
        if (mTotalMarketPrice != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += Utils.subTwoNumber(mTotalMarketPrice);
                price += "积分";
            } else {
                price += Utils.subTwoNumber(mTotalMarketPrice);
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "0.00";
        }
        return price;
    }

    @NotNull
    private String getPrice(double totalPrice) {
        String price = "";
        if (totalPrice != 0.00) {
            price += "¥";
            price += Utils.subTwoNumber(totalPrice);
        }
        if (mTotalMarketPrice != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += Utils.subTwoNumber(mTotalMarketPrice);
                price += "积分";
            } else {
                price += Utils.subTwoNumber(mTotalMarketPrice);
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "¥0.00";
        }
        return price;
    }

    @OnClick({R.id.rl_address, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_address://地址
                AddressActivity.go(this, 1001, mAid, String.valueOf(mFirmOrderBean.getShaddressMap().getId()));
                break;
            case R.id.btn_submit:
                if ("-1".equals(mAid)) {
                    ToastUtils.showToast("请添加收货地址");
                    return;
                }
                if (mFirmGoodsBeans.size() > 0 && goodsList.size() > 0) {
                    ToastUtils.showToast("预售商品请单独提交");
                    return;
                }
                if (mFirmGoodsBeans.size() > 1) {
                    ToastUtils.showToast("开售时间不同，请分开提交");
                    return;
                }
                submitFirmOrder();
                break;
        }
    }

    private void submitFirmOrder() {
        if (!TextUtils.isEmpty(mCid)) {
            final String remark = mEtRemark.getText().toString().trim();
            final List<FirmOrderBean.ProductMapBean> carList = mFirmOrderBean.getCarList();
            if (carList != null && carList.size() > 0) {
                List<Map<String, String>> mapList = new ArrayList<>();
                for (int index = 0; index < carList.size(); index++) {
                    final FirmOrderBean.ProductMapBean productMapBean = carList.get(index);
                    Map<String, String> map = new HashMap<>();
                    map.put("productId", String.valueOf(productMapBean.getProduct_id()));
                    map.put("attributeId", String.valueOf(productMapBean.getAttribute_id()));
                    map.put("freightId", productMapBean.getFreightid() + "");
                    map.put("num", productMapBean.getNum() + "");
                    mapList.add(map);
                }
                mPresenter.detailSubmit(this, mapList.toString(), mAid, remark);
            }
        } else if (!TextUtils.isEmpty(mGid)) {
            final String remark = mEtRemark.getText().toString().trim();
            Map<String, String> map = new HashMap<>();
            map.put("productId", mGid);
            map.put("attributeId", mFirmOrderBean.getGmap().getId() + "");
            map.put("freightId", mFirmOrderBean.getFreightid() + "");
            map.put("num", mGoodsNum + "");
            List<Map<String, String>> mapList = new ArrayList<>();
            mapList.add(map);
            mPresenter.detailSubmit(this, mapList.toString(), mAid, remark);
        }
    }

    private void showSportsHarmDialog(final OrderBean orderBean) {
        PaySelectDialog mSportsHarmDialog = new PaySelectDialog(this, 2);
        mSportsHarmDialog.setData(getPriceSpace(mTotalPriceW), orderBean.getKtmap().getBalance());
        mSportsHarmDialog.setOnDialogListener(new PaySelectDialog.onDialogListener() {
            @Override
            public void onConfirm(int type, String payPwd) {
                payType = type;
                mPresenter.onPay(ScheduledOrderActivity.this, orderBean.getOrderId(), type, payPwd);
            }

            @Override
            public void onCancel() {
                finish();
                Intent starter = new Intent(ScheduledOrderActivity.this, DeliveryListActivity.class);
                startActivity(starter);
            }
        });
        mSportsHarmDialog.toggleDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK && data != null) {
            AddressBean bean = (AddressBean) data.getSerializableExtra("data");
            if (bean == null) {
                ToastUtils.showToast("地址选择失败!");
                return;
            }

            //地址
            mTvName.setText(bean.getConsignee());
            final String contactnumber = bean.getContactnumber();
            final String phonestr = contactnumber.substring(0, 3) + "****" + contactnumber.substring(contactnumber.length() - 4);
            mTvMobile.setText(phonestr);
            if (1 == bean.getIsdefault()) {
                mTvDefault.setVisibility(View.VISIBLE);
            } else {
                mTvDefault.setVisibility(View.GONE);
            }
            mTvEmpty.setVisibility(View.GONE);
            mIvFirmRight.setImageResource(R.mipmap.firm_right_arrow);
            mIvFirmLocation.setVisibility(View.VISIBLE);
            mLlUserInfo.setVisibility(View.VISIBLE);

            String address = "";
            if (bean.getArea0id().equals(bean.getArea1id())) {
                address = bean.getArea1name() + bean.getArea2name() + bean.getXxaddress();
            } else {
                address = bean.getArea0name() + bean.getArea1name() + bean.getArea2name() + bean.getXxaddress();
            }
//            mTvAddress.setText(bean.getXxaddress());
            mTvAddress.setText(address);
            mAid = String.valueOf(bean.getId());
            mArea0id = Integer.parseInt(bean.getArea0id());
            mArea1id = Integer.parseInt(bean.getArea1id());
            mArea2id = Integer.parseInt(bean.getArea2id());
            hasAddress = true;
            initFreight(mFirmOrderBean.getCarList(), mTvExpressDelivery);
            reLoadFreight();
            if (!hasAddress) {
                mTotalPriceW = mTotalPrice;
            } else {
                mTotalPriceW = mTotalPrice + mFreight;
            }
            mTvRealPayment.setText(getPrice(mTotalPriceW));
        }
    }

    private void reLoadFreight() {
        if (!TextUtils.isEmpty(mCid)) {
            if (goodsList.size() > 0) {
                if (!hasAddress) {
                    mTvExpressDelivery.setText("运费 ¥0.0");
                } else {
                    final double goodsFreight = proccessCarFreight(goodsList);
                    if (goodsFreight != 0.00) {
                        mTvExpressDelivery.setText("运费 ¥" + Utils.subTwoNumber(goodsFreight));
                    } else {
                        mTvExpressDelivery.setText("包邮");
                    }
                }
            }
        }
        if (mFirmGoodsBeans.size() > 0) {
            for (int i = 0; i < mFirmGoodsBeans.size(); i++) {
                FirmGoodsBean firmGoodsBean = mFirmGoodsBeans.get(i);
                TextView tvExpressDelivery = mTextViews.get(i);
                if (!hasAddress) {
                    mTvExpressDelivery.setText("运费 ¥0.0");
                } else {
                    double goodsFreight = 0.0;
                    final CarInfoBean carInfoBean = getCarInfoBean(firmGoodsBean.getCarList());
                    if (!TextUtils.isEmpty(mCid)) {
                        goodsFreight = proccessCarFreight(firmGoodsBean.getCarList());
                    } else if (!TextUtils.isEmpty(mGid)) {
                        goodsFreight = proccessGoodsFreight(carInfoBean.getNum());
                    }
                    if (goodsFreight != 0.00) {
                        tvExpressDelivery.setText("运费 " + "¥" + Utils.subTwoNumber(goodsFreight));
                    } else {
                        tvExpressDelivery.setText("包邮");
                    }
                }
            }
        }
    }

}